package hibernatemock;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.GeneratedValue;
import javax.persistence.Transient;

public class MappedFieldsLookup {

	public Set<Field> lookupMappedFields(Class<?> clazz) {
		Set<Field> mappedFields = new HashSet<Field>();
		for (Field field : clazz.getDeclaredFields())
			if (!(Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())))
				if (!fieldOrGetterHasAnnotation(clazz, field, Transient.class) && !fieldOrGetterHasAnnotation(clazz, field, GeneratedValue.class))
					mappedFields.add(field);
		return mappedFields;
	}

	private boolean fieldOrGetterHasAnnotation(Class<?> clazz, Field field, Class<? extends Annotation> annotation) {
		if (field.isAnnotationPresent(annotation))
			return true;
		try {
			String getterName = "get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
			Class<?>[] parameter = null;
			return clazz.getMethod(getterName, parameter).isAnnotationPresent(annotation);
		} catch (Exception e) {
			return false;
		}
	}

}
